#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

#include <BoseCmd.h>
#include "CmdSocket.h"


#ifdef USING_UNIX_DOMAIN_SOCKET
#define BOSE_CMD_SOCKET_ID "/dev/bosecmd_socket"
#elif defined(USING_INET_SOCKET)
#define BOSE_CMD_SOCKET_ID (10086)
#endif


#undef TAG
#define TAG "BOSECMDSRV"
#ifdef __ANDROID__
#include <android/log.h>
#define BOSE_LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define BOSE_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define BOSE_LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define BOSE_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#else
#define BOSE_LOGI(str, ...) do{printf("BOSECMDSRV ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define BOSE_LOGD(str, ...) do{printf("BOSECMDSRV ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define BOSE_LOGW(str, ...) do{printf("BOSECMDSRV ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define BOSE_LOGE(str, ...) do{printf("BOSECMDSRV ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#endif

using namespace com::bose;

CmdSocketServer * server {NULL};

static void bosecmd_signal_handler(int signal) {
    unsigned int option = 0;
    switch(signal) {
        case SIGPIPE:   //important, ignore broken pipe
            BOSE_LOGE("received signal SIGPIPE");
            return;
        case SIGCHLD:
        default:        //other singals
            BOSE_LOGE("received signal 0x%X, exiting...", signal);
            return;
    }

EXIT:
    if (NULL != server) {
        delete server;
    }

    exit(0);
}


static void startSocketServer(const int port) {
    server = (CmdSocketServer*)new CmdSocketServer(port, BoseCmd::sh, 0);
    if (server->service_listen() < 0) {
        BOSE_LOGE("service listen(%d) failed", port);
    } else {
        server->startProcess();
    }
}

int main(int argc, char * argv[]) {

    if (argc >= 2) {
        BOSE_LOGI("cmd: %s", argv[1]);
    }

#ifndef __ANDROID__
    int ret;
    ret = system("fuser -v -n tcp 10086 -k");
    BOSE_LOGD("fuser -v -n tcp 10086, ret=%d", ret);
#endif

    signal(SIGPIPE, bosecmd_signal_handler);


    int port = BOSE_CMD_SOCKET_ID;
    if (argc >= 2) {
        port =  atoi(argv[1]);
    }

    if(port > 1000) {
        startSocketServer(port);
    }

    BOSE_LOGD("exit");
    return 0;
}
